package com.music.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Description :
 * Author : 91658
 * Date : 2018/6/22 17:58
 **/
public class SessionFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
//        HttpServletRequest request = (HttpServletRequest) req;
//        HttpServletResponse response = (HttpServletResponse) res;
//
//        // 不过滤的url
//        String[] notFilter = new String[] { "/login","/login/user_login"};
//        String uri = request.getRequestURI();
//        boolean doFilter = true;
//        for (String s : notFilter) {
//            if (uri.indexOf(s) != -1) {
//                // 如果uri中包含不过滤的uri,则不进行过滤
//                doFilter = false;
//                break;
//            }
//        }
//
//        if (doFilter) {
//            //  执行过滤
//            //  从session中获取登录者实体
//            Object obj =  null;
//            if(obj == null){
//                obj = request.getSession().getAttribute("user");
//            }
//            if (obj == null) {
//                boolean isAjaxRequest = isAjaxRequest(request);
//                if (isAjaxRequest) {
//                    response.setCharacterEncoding("UTF-8");
//                    response.sendError(HttpStatus.UNAUTHORIZED.value(),
//                            "您已经太长时间没有操作,请刷新页面");
//                    return;
//                }
//                response.sendRedirect("/");
//                return;
//            } else {
//                // 如果session中存在登陆实体，则继续
//                chain.doFilter(request, response);
//            }
//        } else {
//            chain.doFilter(request, response);
//        }

        // --------------
        //        HttpSession session = request.getSession(false);
//
//        //判断session是否过期
//        if ((User) session.getAttribute("user") == null) {
//            String errors = "您还没有登录，或者session已过期。请先登陆!";
//            request.setAttribute("Message", errors);
//            //跳转至登录页面
//            request.getRequestDispatcher("/login").forward(request, response);
//        } else {
//            chain.doFilter(request, response);
//        }
//        chain.doFilter(request, response);
        chain.doFilter(req, res);
    }
    /**
     * 判断是否为Ajax请求
     * @param request
     * @return
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        if (header != null && "XMLHttpRequest".equals(header)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void destroy() {

    }
}
